#include "head.h"
/* Usage:  */
// 通过本地socket向对应的子进程发一个net_fd信息
// 第一个参数：main进程和工作进程用来通信的本地文件描述符
// 第二个参数：main进程accept的客户端连接对象的文件描述符
int sendMsg(int local_socket, int net_fd)
{
    // 接收到的详细信息
    struct msghdr msg;
    bzero(&msg,sizeof(msg));

    // 准备正文信息
    char *str = "hello";
    struct iovec vec[1];
    vec[0].iov_base=  str;  // 一个数据的指针
    vec[0].iov_len = sizeof(str);   // 数据的长度

    msg.msg_iov =vec;
    msg.msg_iovlen = 1;
    
    // 准备控制信息
    struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type=  SCM_RIGHTS;    //  消息的类型

    void *p =CMSG_DATA(cms);
    int *fd = (int *)p;
    *fd = net_fd;

    msg.msg_control = cms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));

    sendmsg(local_socket, &msg, 0);
    return 0;
}

// 子进程读取父进程通过本地socket发过来的客户端socket对象
// 第一个参数：main进程和工作进程用来通信的本地文件描述符
// 第二个参数：客户端连接对象的文件描述符指针
int recvMsg(int local_socket, int *net_fd)
{
    struct msghdr msg;
    bzero(&msg, sizeof(msg));

    char str[60] = { 0 };
    struct iovec vec[1];
    vec[0].iov_base = str;
    vec[0].iov_len = sizeof(str);

    struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len  = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;

    msg.msg_control = cms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));

    recvmsg(local_socket, &msg, 0);

    void *p = CMSG_DATA(cms);
    int *fd = (int *)p;

    *net_fd = *fd;

    return 0;
}


